package com.bdqn.zhang.dao;

import com.bdqn.zhang.entity.Category;
import com.bdqn.zhang.entity.Entry;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import java.util.List;

public class EntryDaoImpl extends HibernateDaoSupport implements EntryDao{

    @Override
    public void addEntry(Entry entry) {

    }

    @Override
    public void delEntry(Integer id) {

    }

    @Override
    public void updateEntry(Entry entry) {

    }

    @Override
    public Entry findEntry(Entry entry) {
        return null;
    }

    @Override
    public List<Entry> findAllEntries(final Long cId,final Integer page, final Integer limit) {
        return this.getHibernateTemplate().execute(new HibernateCallback<List<Entry>>() {
            @Override
            public List<Entry> doInHibernate(Session session) throws HibernateException {
                return session.createQuery("from Entry e inner join fetch e.category where e.category.id = :cid order by e.id asc").setParameter("cid",cId).setFirstResult((page-1)*limit).setMaxResults(limit).list();
            }
        });
    }

    @Override
    public Long getEntryCount(final Long cId) {
        return this.getHibernateTemplate().execute(new HibernateCallback<Long>() {
            @Override
            public Long doInHibernate(Session session) throws HibernateException {
                return (Long)session.createQuery("select count(1) from Entry e inner join fetch e.category where e.category.id = :cid order by e.id asc").setParameter("cid",cId).uniqueResult();
            }
        });
    }

    /**
     * Criteria查询也叫做 QBC查询   query by criteria
     * https://www.cnblogs.com/gx-java/p/5903814.html
     * https://www.cnblogs.com/zhangzongle/p/5796499.html
     */
    @Override
    public List<Entry> findAllEntries2(final Integer page, final Integer limit) {
        return this.getHibernateTemplate().execute(new HibernateCallback<List<Entry>>() {
            @Override
            public List<Entry> doInHibernate(Session session) throws HibernateException {
                return session.createCriteria(Entry.class,"e").createAlias("category","c").add(Restrictions.ilike("c.name", "经济", MatchMode.ANYWHERE)).setFirstResult((page-1)*limit).setMaxResults(limit).list();
            }
        });
    }

    @Override
    public List<Category> getCategory() {
        return (List<Category>)this.getHibernateTemplate().find("from Category");
    }
}
